package com.superb.common.database;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.superb.common.database.handler.MybatisPlusMetaObjectHandler;
import com.superb.common.database.inner.DelLineInnerInterceptor;
import com.superb.common.database.inner.SuperbParamsInnerInterceptor;
import com.superb.common.database.interceptor.*;
import com.superb.common.database.resolver.SqlFilterArgumentResolver;
import com.superb.common.properties.SuperbCustomProperties;
import jakarta.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @Author: ajie
 * @CreateTime: 2024-05-07 15:33
 */
@Configuration(proxyBeanMethods = false)
public class MybatisAutoConfiguration implements WebMvcConfigurer {

    @Resource
    private SuperbCustomProperties customProperties;

    /**
     * SQL 过滤器避免SQL 注入
     * @param resolvers
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new SqlFilterArgumentResolver());
    }


    /**
     * 分页插件, 对于单一数据库类型来说,都建议配置该值,避免每次分页都去抓取数据库类型
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new SuperbTenantInnerInterceptor(customProperties.getIgnoreTenantTable(), customProperties.getBaseTenant())));
        interceptor.addInnerInterceptor(new DelLineInnerInterceptor(new SuperbDelInnerInterceptor(customProperties.getIgnoreDelTable())));
        interceptor.addInnerInterceptor(new SuperbParamsInnerInterceptor(customProperties.getFieldEncryKey()));
        // 索引检查插件
        interceptor.addInnerInterceptor(new SuperbIndexCheckInterceptor(customProperties));
        return interceptor;
    }

    @Bean
    public String superbMyBatisInterceptor(SqlSessionFactory sqlSessionFactory) {
        sqlSessionFactory.getConfiguration().addInterceptor(new SuperbEncryptInterceptor(customProperties.getFieldEncryKey()));
        sqlSessionFactory.getConfiguration().addInterceptor(new SuperbDecryptInterceptor(customProperties.getFieldEncryKey()));
        // 添加数据权限拦截器
        sqlSessionFactory.getConfiguration().addInterceptor(new SuperbDataScopeInterceptor());
        return "superbMyBatisInterceptor";
    }

    /**
     * 审计字段自动填充
     * @return
     */
    @Bean
    public MybatisPlusMetaObjectHandler mybatisPlusMetaObjectHandler() {
        return new MybatisPlusMetaObjectHandler();
    }


}
